package com.keyroy.game.puzzle_rpg.views.listener;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

public abstract class TextTableListener implements TableListener {

	@Override
	public void onSelected(Table table, final TableEditor tableEditor, final TableItem tableItem, final int editIndex) {
		final Text text = new Text(table, SWT.BORDER);
		text.setText(tableItem.getText(editIndex));
		text.addFocusListener(new FocusAdapter() {
			public void focusLost(FocusEvent e) {
				if (onValueChange(text.getText())) {
					TableItem tableItem = tableEditor.getItem();
					tableItem.setText(editIndex, text.getText());
				}
				text.dispose();
			}
		});
		tableEditor.setEditor(text, tableItem, editIndex);
		text.selectAll();
		text.forceFocus();
		tableItem.setText(editIndex, "");
	}

	public abstract boolean onValueChange(String text);

}
